<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <FeedbackSearchBar @search="handleSearch" :currentPage="currentPage" :pageSize="pageSize" />
      </div>
    </template>
    <el-config-provider :locale="locale">
      <el-table
        :data="tableData"
        :row-class-name="tableRowClassName"
        height="440"
        :default-sort="{ prop: 'fDate', order: 'ascending' }"
        row-key="id"
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <!-- table部分 -->
        <el-table-column prop="feedbackId" label="反馈信息编号" width="120px" />
        <el-table-column prop="feedbackUserName" label="反馈者姓名" width="120px">
          <template #default="scope">
            {{ scope.row.feedbackUserName ? scope.row.feedbackUserName : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="province" label="省份" width="120px">
          <template #default="scope">
            {{ scope.row.province ? scope.row.province : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="city" label="城市" width="120px">
          <template #default="scope">
            {{ scope.row.city ? scope.row.city : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" width="120px">
          <template #default="scope">
            {{ scope.row.address ? scope.row.address : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="rankId" label="预估污染等级">
          <template #default="scope">
            <p v-if="scope.row.rankId == '1'" style="color: #67c23a">优（一）</p>
            <p v-if="scope.row.rankId == '2'" style="color: #ffff00">良好（二）</p>
            <p v-if="scope.row.rankId == '3'" style="color: #ffa500">轻度污染（三）</p>
            <p v-if="scope.row.rankId == '4'" style="color: #ff0000">中度污染（四）</p>
            <p v-if="scope.row.rankId == '5'" style="color: #800080">重度污染（五）</p>
            <p v-if="scope.row.rankId == '6'" style="color: #800000">严重污染（六）</p>
          </template>
        </el-table-column>
        <el-table-column prop="feedbackTime" label="反馈日期" sortable />
        <el-table-column
          prop="isAssigned"
          label="状态"
          :filters="[
            { text: '未指派', value: 0 },
            { text: '已指派', value: 1 },
            { text: '已确认', value: 2 }
          ]"
          :filter-method="filterState"
          filter-placement="bottom-end"
        >
          <template #default="scope">
            <p v-if="scope.row.isAssigned == '0'" style="color: #ff0000">
              <el-icon :style="iconStyle"> <CircleCloseFilled /> </el-icon>未指派
            </p>
            <p v-if="scope.row.isAssigned == '1'" style="color: #ffa500">
              <el-icon :style="iconStyle"> <WarningFilled /> </el-icon>已指派
            </p>
            <p v-if="scope.row.isAssigned == '2'" style="color: #67c23a">
              <el-icon :style="iconStyle"> <SuccessFilled /> </el-icon>已确认
            </p>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="text-align: -webkit-center">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :small="small"
          :page-sizes="[6, 7, 8, 9, 10]"
          :background="background"
          layout="prev, pager, next, jumper,sizes,total"
          v-model:total="total"
          @current-change="handleCurrentChange"
          @size-change="handleCurrentChange"
          style="width: max-content; margin-top: 50px"
        />
      </div>
    </el-config-provider>
  </el-card>
</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import $axios from '../utils/axios'
import { ElNotification } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import en from 'element-plus/dist/locale/en.mjs'

import FeedbackSearchBar from './FeedbackSearchBar.vue'
import AddressSelect from '../supervisor/addressSelect.vue'
import { useRouter } from 'vue-router'

const language = ref('zh-cn')
const locale = computed(() => (language.value === 'zh-cn' ? zhCn : en))
const router = useRouter()

const size = ref('')
const iconStyle = computed(() => {
  const marginMap = {
    large: '10px',
    default: '6px',
    small: '4px'
  }
  return {
    marginRight: marginMap[size.value] || marginMap.default
  }
})
//斑马条样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 1 ? 'success-row' : ''
}

//按状态筛选
const filterState = (value, row) => {
  return row.state === value
}

const remote = ref(true)
const visible = ref(false)
//向搜索栏组件传值
const labelWidth1 = '100px'
let selectWidth = '120px'
let labelWidth = '100px'

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref('')
const background = ref(true)

const formAssign = ref({})

const tableData = ref([])

const girmanDisabled = ref(true)
const gridmans = ref({})
const updateFrom = ref({})

//获得子组件条件查询结果
const handleSearch = (data, current, size, tt) => {
  tableData.value = data
  currentPage.value = current
  pageSize.value = size
  total.value = tt
}

// 初始化
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})
const handleCurrentChange = async () => {
  const path = '/api/feedback/queryFeedback'
  const response = await $axios.post(path, { ...queryParams }, {})
  console.log(response)
  if (response.data.code === '200') {
    console.log(response)
    tableData.value = response.data.data.list
    total.value = response.data.data.total
  }
}
handleCurrentChange()

const handleRowClick = (row) => {
  router.push({ name: 'feedbackDetail', params: { id: row.feedbackId } })
}

//向省市县组件传值，查找对应的网格员
const selectChanged = async (f, lw, sw) => {
  formAssign.value = f
  labelWidth = lw
  selectWidth = sw
  // visible.value = true
  girmanDisabled.value = false
  // const tId = formAssign.value.tId
  const path = '/user/findGridmanByTid/' + formAssign.value.town.id
  const { data: res } = await $axios.get(path)
  if (res.code === 200) {
    gridmans.value = res.result
  }
  console.log(gridmans.value)
  console.log(formAssign.value)
}

// 获取当前指派时间
function dateFormat() {
  var now = new Date()
  var year = now.getFullYear()
  var month = now.getMonth() + 1 < 10 ? '0' + (now.getMonth() + 1) : now.getMonth() + 1
  var day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
  var hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours()
  var minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
  var second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
  updateFrom.value.assignDate = year + '-' + month + '-' + day
  updateFrom.value.assignTime = hour + ':' + minute + ':' + second
}

const updateGrid = ref({})

// 指派给网格员
const onAssign = async (row) => {
  console.log('指派')
  // console.log(row);
  dateFormat()
  updateFrom.value.id = row.id
  updateFrom.value.state = 1
  console.log(updateFrom.value)
  const path = '/feedback/update'
  const { data: res } = await $axios.post(path, updateFrom.value)
  if (res.code === 200) {
    visible.value = false
    updateGrid.value.id = updateFrom.value.gId
    updateGrid.value.state = 1
    const path = '/user/update'
    const { data: res } = await $axios.post(path, updateGrid.value)
    if (res.code === 200) {
      console.log('已修改网格员状态')
    }
    handleCurrentChange()
    ElNotification({
      title: '成功',
      message: '已成功指派网格员！',
      type: 'success'
    })
  } else if (res.code === 103) {
    ElNotification({
      title: '失败',
      message: '未知原因，指派网格员失败！',
      type: 'error'
    })
  }
}
</script>

<style scoped>
.box-card {
  width: 99%;
  height: 95%;
  margin-top: 12px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.descriptions {
  margin-top: 20px;
}
</style>

<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
